package com.android.gufengmall.admin;

import android.content.Intent;
import android.content.pm.ActivityInfo;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.os.Bundle;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.Toast;

import androidx.activity.result.ActivityResultLauncher;
import androidx.activity.result.contract.ActivityResultContracts;
import androidx.appcompat.app.AlertDialog;
import androidx.fragment.app.Fragment;
import androidx.recyclerview.widget.DividerItemDecoration;
import androidx.recyclerview.widget.LinearLayoutManager;
import androidx.recyclerview.widget.RecyclerView;

import com.android.gufengmall.App;
import com.android.gufengmall.R;
import com.android.gufengmall.adapter.MallManagerAdapter;
import com.android.gufengmall.bean.GoodsBean;
import com.android.gufengmall.gen.DaoSession;
import com.android.gufengmall.gen.GoodsBeanDao;
import com.android.gufengmall.utils.BitMapConversionUtils;
import com.android.gufengmall.utils.GlideEngine;
import com.luck.picture.lib.PictureSelector;
import com.luck.picture.lib.config.PictureConfig;
import com.luck.picture.lib.config.PictureMimeType;
import com.luck.picture.lib.entity.LocalMedia;
import com.luck.picture.lib.entity.MediaExtraInfo;
import com.luck.picture.lib.style.PictureSelectorUIStyle;
import com.luck.picture.lib.tools.MediaUtils;

import java.util.ArrayList;
import java.util.List;

/**
 * 商品管理
 */
public class MallManagerFragment extends Fragment implements MallManagerAdapter.onCheckSelectListener {

    private static final String TAG = "MallManagerFragment";

    private RecyclerView mRvMallManager;
    private MallManagerAdapter mMallManagerAdapter;
    private ActivityResultLauncher<Intent> launcherResult;
    private ActivityResultLauncher<Intent> updateLauncherResult;

    private ArrayList<GoodsBean> mGoodsBeans = new ArrayList<>();
    private ArrayList<Integer> mSelectCheckBox = new ArrayList<>();
    private App mMyApp;
    private DaoSession mDaoSession;
    private GoodsBeanDao mGoodsBeanDao;

    private Button mBtnAdd;
    private Button mBtnDelete;
    private Button mBtnUpdate;
    private EditText mEdtName;
    private EditText mEdtInfo;
    private EditText mEdtPrice;
    private ImageView mImgAdd;
    private ImageView mUpdateImgAdd;
    private EditText mEdtNum;
    private Bitmap mBitmap;
    private String mRealPath;
    private String mUpdateRealPath;

    public static MallManagerFragment newInstance() {
        return new MallManagerFragment();
    }

    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
    }

    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container,
                             Bundle savedInstanceState) {
        View view = inflater.inflate(R.layout.fragment_mall_manager, container, false);
        initView(view);
        initData();
        initListener();
        return view;
    }

    private void initListener() {
        mBtnAdd.setOnClickListener(v -> {
            AlertDialog.Builder dialog = new AlertDialog.Builder(requireContext());
            dialog.setTitle("添加商品");
            View view = LayoutInflater.from(requireContext()).inflate(R.layout.dialog_add_mall_manager, null, false);
            mEdtName = view.findViewById(R.id.et_name);
            mEdtInfo = view.findViewById(R.id.et_info);
            mEdtPrice = view.findViewById(R.id.et_price);
            mImgAdd = view.findViewById(R.id.img_add);
            mEdtNum = view.findViewById(R.id.et_num);
            mImgAdd.setOnClickListener(v1 -> {
                PictureSelector.create(MallManagerFragment.this)
                        .openGallery(PictureMimeType.ofImage())
                        .imageEngine(GlideEngine.createGlideEngine())// 外部传入图片加载引擎，必传项
                        .setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_UNSPECIFIED)// 设置相册Activity方向，不设置默认使用系统
                        .setPictureUIStyle(PictureSelectorUIStyle.ofDefaultStyle())
                        .selectionMode(PictureConfig.SINGLE)// 单选
                        .isSingleDirectReturn(true)// 单选模式下是否直接返回
                        .isCamera(true)
                        .isPreviewImage(true)// 可预览图片
                        .isZoomAnim(true)// 图片列表点击 缩放效果
                        .forResult(launcherResult);
            });
            dialog.setNegativeButton("取消", null);
            dialog.setPositiveButton("确定", (dialog1, which) -> {
                String name = mEdtName.getText().toString().trim();
                String info = mEdtInfo.getText().toString().trim();
                String price = mEdtPrice.getText().toString().trim();
                String num = mEdtNum.getText().toString().trim();
                if (name.isEmpty() || info.isEmpty() || price.isEmpty() || num.isEmpty()) {
                    Toast.makeText(requireContext(), "添加内容不能为空", Toast.LENGTH_SHORT).show();
                } else {
                    boolean isAdd = true;
                    for (int i = 0; i < mGoodsBeans.size(); i++) {
                        GoodsBean goodsBean = mGoodsBeans.get(i);
                        if (goodsBean.getGoods_info().equals(info)) {
                            isAdd = false;
                        }
                    }
                    if (isAdd) {
                        GoodsBean goodsBean = new GoodsBean();
                        goodsBean.setGoods_name(name);
                        goodsBean.setGoods_info(info);
                        goodsBean.setGoods_price(Double.parseDouble(price));
                        goodsBean.setGoods_amount(Integer.parseInt(num));
                        goodsBean.setGoods_imgShop(mRealPath);
                        mGoodsBeanDao.insert(goodsBean);
                        mGoodsBeans.add(goodsBean);
                        Toast.makeText(requireContext(), "添加成功", Toast.LENGTH_SHORT).show();
                        mMallManagerAdapter.notifyDataSetChanged();
                        dialog1.dismiss();
                    } else {
                        Toast.makeText(requireContext(), "添加失败，商品已存在", Toast.LENGTH_SHORT).show();
                    }
                }
            });
            dialog.setView(view);
            dialog.create().show();
        });

        mBtnDelete.setOnClickListener(v -> {
            boolean isDelete = false;
            for (int i = 0; i < mSelectCheckBox.size(); i++) {
                Integer index = mSelectCheckBox.get(i);
                GoodsBean goodsBean = mGoodsBeans.get(index);
                mGoodsBeanDao.delete(goodsBean);
                mGoodsBeans.remove(goodsBean);
                mSelectCheckBox.remove(index);
                isDelete = true;
            }
            if (isDelete) {
                Toast.makeText(requireContext(), "删除成功", Toast.LENGTH_SHORT).show();
                mMallManagerAdapter.notifyDataSetChanged();
            } else {
                Toast.makeText(requireContext(), "删除失败", Toast.LENGTH_SHORT).show();
            }
        });
        mBtnUpdate.setOnClickListener(v -> {
            if (mSelectCheckBox.size() != 1) {
                Toast.makeText(requireContext(), "请选择一个数据进行修改，不可多选或少选", Toast.LENGTH_SHORT).show();
            } else {
                GoodsBean goodsBean = mGoodsBeans.get(mSelectCheckBox.get(0));
                AlertDialog.Builder dialog = new AlertDialog.Builder(requireContext());
                dialog.setTitle("修改商品");
                View view = LayoutInflater.from(requireContext()).inflate(R.layout.dialog_add_mall_manager, null, false);
                mEdtName = view.findViewById(R.id.et_name);
                mEdtInfo = view.findViewById(R.id.et_info);
                mEdtPrice = view.findViewById(R.id.et_price);
                mUpdateImgAdd = view.findViewById(R.id.img_add);
                mEdtNum = view.findViewById(R.id.et_num);
                mEdtName.setText(goodsBean.getGoods_name());
                mEdtInfo.setText(goodsBean.getGoods_info());
                mUpdateImgAdd.setImageBitmap(BitMapConversionUtils.stringToBitmap(goodsBean.getGoods_imgShop()));
                mEdtPrice.setText(goodsBean.getGoods_price() + "");
                mEdtNum.setText(goodsBean.getGoods_amount() + "");
                mUpdateImgAdd.setOnClickListener(v1 -> {
                    PictureSelector.create(MallManagerFragment.this)
                            .openGallery(PictureMimeType.ofImage())
                            .imageEngine(GlideEngine.createGlideEngine())// 外部传入图片加载引擎，必传项
                            .setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_UNSPECIFIED)// 设置相册Activity方向，不设置默认使用系统
                            .setPictureUIStyle(PictureSelectorUIStyle.ofDefaultStyle())
                            .selectionMode(PictureConfig.SINGLE)// 单选
                            .isSingleDirectReturn(true)// 单选模式下是否直接返回
                            .isCamera(true)
                            .isPreviewImage(true)// 可预览图片
                            .isZoomAnim(true)// 图片列表点击 缩放效果
                            .forResult(updateLauncherResult);
                });
                dialog.setNegativeButton("取消", null);
                dialog.setPositiveButton("确定", (dialog1, which) -> {
                    String name = mEdtName.getText().toString().trim();
                    String info = mEdtInfo.getText().toString().trim();
                    String price = mEdtPrice.getText().toString().trim();
                    String num = mEdtNum.getText().toString().trim();
                    if (name.isEmpty() || info.isEmpty() || price.isEmpty() || num.isEmpty()) {
                        Toast.makeText(requireContext(), "修改内容不能为空", Toast.LENGTH_SHORT).show();
                    } else {
                        goodsBean.setGoods_name(name);
                        goodsBean.setGoods_price(Double.parseDouble(price));
                        goodsBean.setGoods_info(info);
                        goodsBean.setGoods_imgShop(mUpdateRealPath);
                        goodsBean.setGoods_amount(Integer.parseInt(num));
                        mGoodsBeanDao.update(goodsBean);
                        Toast.makeText(requireContext(), "修改成功", Toast.LENGTH_SHORT).show();
                        mMallManagerAdapter.notifyDataSetChanged();
                        dialog1.dismiss();
                    }
                });
                dialog.setView(view);
                dialog.create().show();
            }
        });
    }

    //接收到选择的图片
    private ActivityResultLauncher<Intent> createActivityResultLauncher() {
        return registerForActivityResult(new ActivityResultContracts.StartActivityForResult(),
                result -> {
                    int resultCode = result.getResultCode();
                    if (resultCode == -1) {
                        List<LocalMedia> selectList = PictureSelector.obtainMultipleResult(result.getData());
                        for (LocalMedia media : selectList) {
                            if (media.getWidth() == 0 || media.getHeight() == 0) {
                                if (PictureMimeType.isHasImage(media.getMimeType())) {
                                    MediaExtraInfo imageExtraInfo = MediaUtils.getImageSize(media.getPath());
                                    media.setWidth(imageExtraInfo.getWidth());
                                    media.setHeight(imageExtraInfo.getHeight());
                                } else if (PictureMimeType.isHasVideo(media.getMimeType())) {
                                    MediaExtraInfo videoExtraInfo = MediaUtils.getVideoSize(getContext(), media.getPath());
                                    media.setWidth(videoExtraInfo.getWidth());
                                    media.setHeight(videoExtraInfo.getHeight());
                                }
                            }
                            String path = media.getPath();
                            mRealPath = media.getRealPath();
                            Log.i(TAG, "path:" + path + " mRealPath->"+mRealPath);
                            mBitmap = BitmapFactory.decodeFile(mRealPath);
                            mImgAdd.setImageBitmap(mBitmap);
                        }
                    }
                });
    }

    //接收到修改选择的图片
    private ActivityResultLauncher<Intent> createUpdateActivityResultLauncher() {
        return registerForActivityResult(new ActivityResultContracts.StartActivityForResult(),
                result -> {
                    int resultCode = result.getResultCode();
                    if (resultCode == -1) {
                        List<LocalMedia> selectList = PictureSelector.obtainMultipleResult(result.getData());
                        for (LocalMedia media : selectList) {
                            if (media.getWidth() == 0 || media.getHeight() == 0) {
                                if (PictureMimeType.isHasImage(media.getMimeType())) {
                                    MediaExtraInfo imageExtraInfo = MediaUtils.getImageSize(media.getPath());
                                    media.setWidth(imageExtraInfo.getWidth());
                                    media.setHeight(imageExtraInfo.getHeight());
                                } else if (PictureMimeType.isHasVideo(media.getMimeType())) {
                                    MediaExtraInfo videoExtraInfo = MediaUtils.getVideoSize(getContext(), media.getPath());
                                    media.setWidth(videoExtraInfo.getWidth());
                                    media.setHeight(videoExtraInfo.getHeight());
                                }
                            }
                            String path = media.getPath();
                            mUpdateRealPath = media.getRealPath();
                            Log.i(TAG, "path:" + path + " mUpdateRealPath->"+mUpdateRealPath);
                            mBitmap = BitmapFactory.decodeFile(mUpdateRealPath);
                            mUpdateImgAdd.setImageBitmap(mBitmap);
                        }
                    }
                });
    }

    private void initView(View view) {
        mRvMallManager = view.findViewById(R.id.rv_mall_manager);
        mBtnAdd = view.findViewById(R.id.btn_add);
        mBtnDelete = view.findViewById(R.id.btn_delete);
        mBtnUpdate = view.findViewById(R.id.btn_update);
    }

    private void initData() {
        mMyApp = (App) getActivity().getApplication();
        mDaoSession = mMyApp.getDaoSession();
        mGoodsBeanDao = mDaoSession.getGoodsBeanDao();
        mGoodsBeans.addAll(mGoodsBeanDao.loadAll());

        launcherResult = createActivityResultLauncher();
        updateLauncherResult = createUpdateActivityResultLauncher();

        LinearLayoutManager layoutManager = new LinearLayoutManager(requireContext());
        layoutManager.setOrientation(LinearLayoutManager.VERTICAL);
        mRvMallManager.setLayoutManager(layoutManager);

        mMallManagerAdapter = new MallManagerAdapter(requireContext(), mGoodsBeans);
        mMallManagerAdapter.setOnCheckSelectListener(this);
        DividerItemDecoration dividerItemDecoration = new DividerItemDecoration(requireContext(), DividerItemDecoration.VERTICAL);
        mRvMallManager.addItemDecoration(dividerItemDecoration);
        mRvMallManager.setAdapter(mMallManagerAdapter);

    }

    @Override
    public void OnCheckSelect(int position, boolean isCheck) {
        if (isCheck) {
            mSelectCheckBox.add(position);
        } else {
            for (int i = 0; i < mSelectCheckBox.size(); i++) {
                Integer integer = mSelectCheckBox.get(i);
                if (integer == position) {
                    mSelectCheckBox.remove(i);
                }
            }
        }
    }

    @Override
    public void onDestroy() {
        super.onDestroy();
        if (launcherResult != null) {
            launcherResult.unregister();
            updateLauncherResult.unregister();
        }
    }
}